package userserv

import (
	"codedef"
	"config"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"strconv"
)

func onLoadDevice(w http.ResponseWriter, r *http.Request) {
	var uniqueId string
	uniqueId = r.Header.Get("uniqueId")
	cid := r.Header.Get("cid")

	log.Printf("onLoadMain, uniqueId:%s\n", uniqueId)

	if cid == "" {
		log.Println("onLoadDevice failed, controller id is empty")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	if !isUserDeviceExist(uniqueId, cid) {
		log.Println("onLoadDevice failed, controller not exist ", cid)
		replyError(w, codedef.ERR_CONTROLLER_NOT_EXIST)
		return
	}

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	fields, err := redis.Strings(rconn.Do("HMGET", rhelper.ControllerHash+cid, "id", "type", "apptype",
		"deviceName", "deviceVersion", "deviceVersionCode", "firmName", "firmVersion", "firmVersionCode",
		"alias", "remark", "messageNotify", "account", "ctlFlags", "isBindCloseTime", "closeTime", "imgName", "deviceModel", "brand", "serverId"))

	if err != nil && err != redis.ErrNil {
		log.Println(err)
		replyError(w, codedef.ERR_DATABASE)
	}

	d := &Controller{}
	d.Id = fields[0]
	d.CType = fields[1]
	d.AppType = fields[2]
	d.DeviceName = fields[3]
	d.DeviceVersion = fields[4]
	d.DeviceVersionCode = fields[5]

	d.FirmName = fields[6]
	d.FirmVersion = fields[7]
	d.FirmVersionCode = fields[8]

	d.Alias = fields[9]
	d.Remark = fields[10]
	d.MessageNotify = fields[11]
	d.Account = fields[12]
	d.CtlFlags = fields[13]
	d.IsBindCloseTime = convertString2Int(fields[14])
	d.CloseTime = convertString2Int(fields[15])
	d.ImgName = fields[16]
	d.DeviceModel = fields[17]
	d.Brand = fields[18]
	d.ServerId = fields[19]
	d.HasNewFirmVersion = 0
	controllerForm, _ := strconv.ParseFloat(d.FirmVersion, 2)
	if controllerForm < config.LatestFirmVersionCode {
		d.HasNewFirmVersion = 1
	}

	if d.Alias != "" {
		d.DeviceName = d.Alias
	}

	if isControllerOnline(d.ServerId, d.Id) {
		d.Status = "online"
	} else {
		d.Status = "offline"
	}

	replyJSON(w, d)
}

func init() {
	myMux.muxHandlers.HandleFunc("/loadDevice", onLoadDevice)
}
